<template>
  <div class="category-page">
    <!-- 页面头部 -->
    <div class="category-header">
      <div class="container">
        <div class="breadcrumb">
          <el-breadcrumb separator=">">
            <el-breadcrumb-item :to="{ path: '/' }">首頁</el-breadcrumb-item>
            <el-breadcrumb-item>商品分類</el-breadcrumb-item>
            <el-breadcrumb-item>{{ categoryName }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <p class="category-desc">{{ getCategoryDescription() }}</p>
      </div>
    </div>

    <div class="container">
      <div class="category-content">
        <!-- 左侧推荐商品 -->
        <div class="recommend-sidebar">
          <div class="recommend-header">
            <h3 class="recommend-title">
              <el-icon class="title-icon">
                <Star/>
              </el-icon>
              爲你推薦
            </h3>
          </div>

          <div class="recommend-products">
            <div
                v-for="product in randomProducts.slice(0, 6)"
                :key="product.id"
                class="recommend-item"
                @click="goToProduct(product.id)"
            >
              <div class="recommend-image">
                <img :src="product.image" :alt="product.name"/>
                <div class="recommend-tags">
                  <span v-if="product.isHot" class="recommend-tag hot">熱銷</span>
                </div>
              </div>
              <div class="recommend-info">
                <h4 class="recommend-name">{{ product.name }}</h4>
                <div class="recommend-price">
                  <span class="current-price"><Currency/>{{ formatPrice(product.price) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧商品列表 -->
        <div class="product-main">
          <!-- 商品网格视图 -->
          <div v-if="viewMode === 'grid'" class="products-grid">
            <div
                v-for="product in paginatedProducts"
                :key="product.id"
                class="product-card"
                @click="goToProduct(product.id)"
            >
              <div class="product-image">
                <img :src="product.image" :alt="product.name"/>
                <div class="product-tags">
                  <span v-if="product.isNew" class="product-tag new">新品</span>
                  <span v-if="product.isHot" class="product-tag hot">熱銷</span>
                  <span v-if="product.discount" class="product-tag discount">{{ product.discount }}折</span>
                </div>
              </div>
              <div class="product-info">
                <h3 class="product-name">{{ product.name }}</h3>
                <div class="product-meta">
                  <div class="product-rating">
                    <el-rate
                        :model-value="product.rating /2"
                        disabled
                        size="small"
                        show-score
                        text-color="#ff9900"
                        :score-template="`${product.rating}`"
                    />
                    <span class="review-count">({{ product.reviewCount }})</span>
                  </div>
                  <div class="product-sales">已售{{ product.sales }}件</div>
                </div>
                <div class="product-price">
                  <span class="current-price"><Currency/>{{ formatPrice(product.price) }}</span>
                  <span v-if="product.originalPrice" class="original-price"><Currency/>{{
                      formatPrice(product.originalPrice)
                    }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 商品列表视图 -->
          <!--          <div v-else class="product-list">-->
          <!--            <div-->
          <!--                v-for="product in paginatedProducts"-->
          <!--                :key="product.id"-->
          <!--                class="product-item"-->
          <!--                @click="goToProduct(product.id)"-->
          <!--            >-->
          <!--              <div class="product-image">-->
          <!--                <img :src="product.image" :alt="product.name"/>-->
          <!--              </div>-->
          <!--              <div class="product-content">-->
          <!--                <div class="product-main-info">-->
          <!--                  <el-tooltip :content="product.name" placement="top">-->
          <!--                    <h3 class="product-name">{{ product.name }}</h3>-->
          <!--                  </el-tooltip>-->
          <!--                  <p class="product-desc">{{ product.description }}</p>-->
          <!--                  <div class="product-meta">-->
          <!--                    <div class="product-rating">-->
          <!--                      <el-rate-->
          <!--                          :model-value="product.rating / 2"-->
          <!--                          disabled-->
          <!--                          size="small"-->
          <!--                          show-score-->
          <!--                          text-color="#ff9900"-->
          <!--                          :score-template="`${product.rating}`"-->
          <!--                      />-->
          <!--                      <span class="review-count">({{ product.reviewCount }})</span>-->
          <!--                    </div>-->
          <!--                    <div class="product-sales">已售{{ product.sales }}件</div>-->
          <!--                  </div>-->
          <!--                </div>-->
          <!--                <div class="product-side">-->
          <!--                  <div class="product-price">-->
          <!--                    <span class="current-price"><Currency/>{{ formatPrice(product.price) }}</span>-->
          <!--                    <span v-if="product.originalPrice" class="original-price"><Currency/>{{-->
          <!--                        formatPrice(product.originalPrice)-->
          <!--                      }}</span>-->
          <!--                  </div>-->
          <!--                </div>-->
          <!--              </div>-->
          <!--            </div>-->
          <!--          </div>-->

          <!-- 分页组件 -->
          <div class="pagination-wrapper">
            <div class="custom-pagination">
              <button
                  class="pagination-btn prev-btn"
                  :disabled="apiPagination.currentPage <= 1"
                  @click="goToPrevPage"
              >
                <el-icon>
                  <ArrowLeft/>
                </el-icon>
                上一頁
              </button>

              <div class="pagination-info">
                第 {{ apiPagination.currentPage }} 頁，共 {{ totalPages }} 頁
              </div>

              <button
                  class="pagination-btn next-btn"
                  :disabled="apiPagination.currentPage >= totalPages"
                  @click="goToNextPage"
              >
                下一頁
                <el-icon>
                  <ArrowRight/>
                </el-icon>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {Star, ArrowLeft, ArrowRight} from '@element-plus/icons-vue'
import {fetchRan, fetchSort} from "@/request/req.ts";
import {commonStore} from '@/store/common.ts'
import {formatPrice} from '@/utils/formatPrice'
import Currency from "@/components/common/Currency.vue";

const route = useRoute()
const router = useRouter()
const common = commonStore()

// 分类名称
const categoryName = computed(() => route.params.category as string)

// 筛选状态
const viewMode = ref<'grid' | 'list'>('grid')

// 分页
const currentPage = ref(1)

// 随机商品数据
const randomProducts = ref<any[]>([])
// API返回的分页信息
const apiPagination = ref({
  totalPages: 0,
  currentPage: 1,
  pageSize: 0
})

/**
 * 随机商品
 */
const loadRandomProducts = async () => {
  try {
    const res = await fetchRan({id: 6})
    if (res && res.Success === 'true' && res.GoodsList) {
      const serverUrlItem = common.getItemById(1)
      const serverUrl = serverUrlItem ? serverUrlItem.value : ''

      randomProducts.value = res.GoodsList.map((item: any) => ({
        id: item.Id,
        name: item.GoodsName,
        description: item.ProductDescription || item.GoodsName,
        price: parseFloat(item.Pirce) || 0,
        originalPrice: parseFloat(item.Pirces?.replace(/,/g, '')) || undefined,
        image: serverUrl + '/images/UpLoadPic/' + item.PicUrls,
        brand: '',
        sales: parseInt(item.SalesVolume) || 0,
        rating: parseFloat((item.StarCount / 2).toFixed(1)) || 0,
        reviewCount: parseInt(item.Views) || 0,
        isNew: false,
        isHot: item.SalesVolume > 0,
        discount: undefined
      }))
    }
  } catch (error) {
    console.error('获取随机商品失败:', error)
  }
}

/**
 * 获取分类数据
 */
const fetchCategoryData = async () => {
  try {
    const res: any = await fetchSort({p: currentPage.value, t: categoryName.value})
    if (res && res.GoodsList) {
      const serverUrlItem = common.getItemById(1)
      const serverUrl = serverUrlItem ? serverUrlItem.value : ''

      // 更新API分页信息
      apiPagination.value = {
        totalPages: parseInt(res.PageCount) || 0,
        currentPage: parseInt(res.Pages) || 1,
        pageSize: parseInt(res.PageNum) || 12
      }

      products.value = res.GoodsList.map((item: any) => {
        return {
          id: item.Id,
          name: item.GoodsName,
          description: item.ProductDescription || item.GoodsName,
          price: parseFloat(item.Pirce) || 0,
          originalPrice: undefined,
          image: serverUrl + '/images/UpLoadPic/' + item.PicUrls,
          brand: '',
          sales: parseInt(item.SalesVolume) || 0,
          rating: item.StarCount,
          reviewCount: parseInt(item.Views) || 0,
          isNew: false,
          isHot: item.IsHot === 1,
          discount: undefined
        }
      })
    }
  } catch (error) {
    console.error('获取分类数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}

// 商品数据
const products = ref<any[]>([])


// 分页后的商品
const paginatedProducts = computed(() => {
  return products.value
})

// 总页数
const totalPages = computed(() => {
  return apiPagination.value.totalPages
})

// 获取分类描述
const getCategoryDescription = () => {
  const descriptions: Record<string, string> = {
    'default': '精選優質商品，滿足寧的各種需求'
  }
  return descriptions[categoryName.value] || descriptions.default
}

// 跳转到商品详情
const goToProduct = (id: number) => {
  router.push(`/product/${id}`)
}

// 上一页
const goToPrevPage = () => {
  if (apiPagination.value.currentPage > 1) {
    currentPage.value = apiPagination.value.currentPage - 1
    fetchCategoryData()
  }
}

// 下一页
const goToNextPage = () => {
  if (apiPagination.value.currentPage < totalPages.value) {
    currentPage.value = apiPagination.value.currentPage + 1
    fetchCategoryData()
  }
}

onMounted(() => {
  fetchCategoryData()
  loadRandomProducts()
})
watch(categoryName, () => {
  // 重置分页
  currentPage.value = 1
  // 重新加载数据
  fetchCategoryData()
})
</script>

<style scoped>
.category-page {
  min-height: 100vh;
  background-color: #1a252f;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 页面头部 */
.category-header {
  background: linear-gradient(135deg, #1a252f 0%, #2c3e50 100%);
  color: white;
  padding: 10px 0;
  margin-bottom: 30px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.breadcrumb :deep(.el-breadcrumb__item) {
  color: #fff;
}

.breadcrumb :deep(.el-breadcrumb__item .el-breadcrumb__inner) {
  color: #fff;
  font-weight: 500;
  transition: color 0.3s ease;
}

.breadcrumb :deep(.el-breadcrumb__item .el-breadcrumb__inner:hover) {
  color: #ff6900;
}

.breadcrumb :deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: #ff6900;
  font-weight: 600;
}

.breadcrumb :deep(.el-breadcrumb__separator) {
  color: #b0b0b0;
  margin: 0 8px;
}

.category-desc {
  font-size: 1.1rem;
  margin: 0;
  opacity: 0.9;
  line-height: 1.6;
}

/* 主要内容区域 */
.category-content {
  display: flex;
  gap: 30px;
}

/* 左侧推荐商品 */
.recommend-sidebar {
  width: 280px;
  flex-shrink: 0;
  background: #2c3e50;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.recommend-header {
  margin-bottom: 20px;
  text-align: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #34495e;
}

.recommend-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.title-icon {
  color: #ff6900;
}

.recommend-products {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.recommend-item {
  background: #34495e;
  border-radius: 6px;
  padding: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.recommend-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  border-color: #ff6900;
}

.recommend-image {
  position: relative;
  width: 100%;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
  flex-shrink: 0;
}

.recommend-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.recommend-item:hover .recommend-image img {
  transform: scale(1.05);
}

.recommend-tags {
  position: absolute;
  top: 4px;
  left: 4px;
}

.recommend-tag {
  padding: 2px 6px;
  border-radius: 6px;
  font-size: 9px;
  font-weight: 500;
  color: white;
  line-height: 1.2;
}

.recommend-tag.hot {
  background: #e74c3c;
}

.recommend-info {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.recommend-name {
  font-size: 11px;
  font-weight: 600;
  color: #ecf0f1;
  margin: 0 0 6px 0;
  line-height: 1.3;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 2.6em;
  flex: 1;
  word-break: break-word;
}

.recommend-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.recommend-price .current-price {
  font-size: 12px;
  font-weight: 700;
  color: var(--primary-color);
}

/* 右侧商品区域 */
.product-main {
  flex: 1;
}

/* 商品网格视图 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.product-card {
  background: #2c3e50;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.product-image {
  position: relative;
  padding-bottom: 75%;
  overflow: hidden;
}

.product-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.product-tags {
  position: absolute;
  top: 8px;
  left: 8px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-tag {
  padding: 4px 8px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 500;
  color: white;
  line-height: 1.2;
}

.product-tag.new {
  background: #27ae60;
}

.product-tag.hot {
  background: #e74c3c;
}

.product-tag.discount {
  background: #f39c12;
}

.product-info {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-name {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  font-size: 16px;
  font-weight: 600;
  color: #ecf0f1;
  margin-bottom: 8px;
  line-height: 1.4;
  overflow: hidden;
}

.product-meta {
  margin-top: auto;
}

.product-rating {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 4px;
}

.review-count {
  font-size: 12px;
  color: #bdc3c7;
}

.product-sales {
  font-size: 12px;
  color: #95a5a6;
}

.product-price {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-top: 12px;
}

.current-price {
  font-size: 20px;
  font-weight: bold;
  color: var(--primary-color);
}

.original-price {
  font-size: 14px;
  color: #95a5a6;
  text-decoration: line-through;
}

.product-item .product-image {
  width: 120px;
  height: 120px;
  flex-shrink: 0;
  position: relative;
  padding-bottom: 0;
}

.product-item .product-image img {
  position: static;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-item .product-name {
  height: auto;
  margin-bottom: 10px;
}

.product-item .product-meta {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

/* 自定义分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 30px 0;
}

.custom-pagination {
  display: flex;
  align-items: center;
  gap: 20px;
}

.pagination-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background-color: #2c3e50;
  color: #d1d1d1;
  border: 1px solid #34495e;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #ff6900;
  color: #fff;
  border-color: #ff6900;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-info {
  color: #d1d1d1;
  font-size: 14px;
  padding: 0 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-content {
    flex-direction: column;
  }

  .recommend-sidebar {
    width: 100%;
    order: 2;
  }

  .product-main {
    order: 1;
  }

  .recommend-products {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
  }

  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 15px;
  }

}
</style>
